package com.xust.oa.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.xust.oa.annotation.PassToken;
import com.xust.oa.domain.dto.LoginDTO;
import com.xust.oa.service.TAdminService;
import com.xust.oa.utils.Result;
import com.xust.oa.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author zj
 * @time 2025/3/24 0:48
 */
@RestController
@RequestMapping
public class LoginController {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

//    @Autowired
//    UserService userService;

    @Autowired
    private TAdminService adminService;


    @Autowired
    private DefaultKaptcha defaultKaptcha;

    /**
     * 登录验证码
     * @param request
     * @param response
     */
    @PassToken
    @GetMapping("/verifyCode")
    public void loginVerifyCode(HttpServletRequest request, HttpServletResponse response) {
// 定义response输出类型为image/jpeg类型
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
// return a jpeg
        response.setContentType("image/jpeg");
        //-------------------生成验证码 begin --------------------------
//获取验证码文本内容
        String text = defaultKaptcha.createText();
//        // 获取会话 ID
        String sessionId = request.getSession().getId();
        System.out.println("当前会话 ID: " + sessionId);
//        + sessionId
        // 将验证码存储到 Redis，使用会话 ID 作为键的前缀
//        redisTemplate.opsForValue().set("verifyCode:"+sessionId , text, 5, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set("verifyCode" , text, 5, TimeUnit.MINUTES);
        System.out.println("验证码内容：" + text);
//根据文本验证码内容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //输出流输出图片，格式为jpg
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //-------------------生成验证码 end --------------------------
    }

    /**
     * 登录
     * @param loginDTO
     * @param request
     * @return
     */

    @PassToken
    @RequestMapping("/login")
    public Result<String> login(@RequestBody LoginDTO loginDTO,HttpServletRequest request) {
        String verifyCode = loginDTO.getVerifyCode();
        // 获取会话 ID
        String sessionId = request.getSession().getId();
        System.out.println("当前会话 ID: " + sessionId);

        // 将验证码存储到 Redis，使用会话 ID 作为键的前缀
//        Object o = redisTemplate.opsForValue().get("verifyCode:" + sessionId);
        Object o = redisTemplate.opsForValue().get("verifyCode");
        if (o == null) {
            return Result.buildFailure(400, "验证码已过期");
        }
        String code = o == null ? "" : o.toString();
        if (!code.equals(verifyCode)) {
            return Result.buildFailure(400, "验证码错误");
        }

        return adminService.login(loginDTO);
    }
    /**
     * 登出
     */

    @PassToken
    @RequestMapping("/logout")
    public Result logout() {
        UserHolder.removeUser();
        redisTemplate.delete("OAUser:token:"+UserHolder.getUser().getId());
        return Result.ok("登出成功");
    }


}
